<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Services\WxShorturlService;

/**
 * 微信短链接管理
 * @package App\Http\Controllers\Admin
 */
class WxShorturlController extends BaseController
{
    private $shorturlSer;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->shorturlSer = new WxShorturlService();
    }

    /**
     * 短链接列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->ajax()){
            $pageSize = $request->get('pageSize', 10);
            $query = \App\Models\WxShorturl::select('*');
            $keyword = $request->get('keyword', '');
            if ($keyword){
                $query->where('name', 'like', '%'.$keyword.'%');
            }
            return $query->paginate($pageSize);
        }
        return view('admin.wxshorturl.index', $this->viewData);
    }
    /**
     * 用户标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\AdminWxShorturlPost $request){
        try {
            $rs = $this->shorturlSer->saveData($request);
            if ($rs) {
                return $this->showMsg('success', ($request->input('tag_id') ? '编辑' : '添加') . '成功',[],  'admin.sysmenu.index');
            }
            throw new \Exception(($request->input('tag_id') ? '编辑' : '添加') . '菜单失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 删除标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            if (!$id) {
                throw new \Exception('请指定要删除的标签');
            }
            $rs = $this->shorturlSer->del($id);
            if (!$rs) {
                throw new \Exception('删除失败');
            }
            return $this->showMsg('success', '删除成功');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
}
